package com.moleq.mgpos.activities;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsoluteLayout;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.moleq.adapter.ItemListAdapter;
import com.moleq.adapter.MixMatchItemAdapter;
import com.moleq.adapter.MixMatchSelectionAdapter;
import com.moleq.base.MoleQBaseActivity;
import com.moleq.base.MoleQBaseDialog;
import com.moleq.device.BaseScanner;
import com.moleq.device.DeviceManager;
import com.moleq.device.DeviceSettingService;
import com.moleq.device.ScannerSetting;
import com.moleq.dialog.DateSettingSelectionDialog;
import com.moleq.dialog.InputDateInfoDialog;
import com.moleq.dialog.InputTimeInfoDialog;
import com.moleq.dialog.ItemDiscountDialog;
import com.moleq.dialog.MessageDialog;
import com.moleq.dialog.TimeSettingSelectionDialog;
import com.moleq.dialog.MessageDialog.OnClickMessageListener;
import com.moleq.itemsetting.tools.MGCreateFiles;
import com.moleq.logic.UPC;
import com.moleq.mgpos.widget.BeepImageButton;
import com.moleq.models.Departmant;
import com.moleq.models.GlobalInfo;
import com.moleq.models.ItemDiscountSetting;
import com.moleq.models.ItemSetting;
import com.moleq.models.MixMatch;
import com.moleq.models.MixMatch_detail;
import com.moleq.models.PosSetting;
import com.moleq.models.PriceSetting;
import com.moleq.service.DepartmantService;
import com.moleq.service.ItemPicService;
import com.moleq.service.ItemSettingService;
import com.moleq.service.MixMatchService;
import com.moleq.service.MixMatchSettingService;
import com.moleq.service.ServiceManager;
import com.moleq.util.MoleQUtil;

public class MixmatchSettingActivity extends MoleQBaseActivity {
	/** Called when the activity is first created. */

	private Dialog DialogWindow = null;

	private List<ItemSetting> list = null;
	private List<MixMatch> mmlist = null;
	private List<MixMatch_detail> mdlist = null;
//	private MixMatch_detail mm_detail;
	private ItemListAdapter itemAdapter;
	private MixMatchSelectionAdapter mmAdapter;
	private MixMatchItemAdapter mmitemAdapter;
	private ListView lv_items,lv_mm_detail_list,lv_mm;
	private MixMatchService mmService;
	private MixMatchSettingService mdService;
	private DepartmantService depService;
	private Spinner sp_list;
	private String[] sp_items;
	private EditText et_search;
	public Button btn_search, btn_update, btn_exit, btn_dialog_ok,
			btn_dialog_cancel;
	private TextView tv_page;
	private ImageButton ibtn_next, ibtn_backpage, ibtn_nextpage,ibtn_price_setting_clear_date,ibtn_clear_dis_link;

	private TextView tv_dupc, tv_dname, tv_ddesc, tv_dprice;
	private ImageView iv_photo;
	private BeepImageButton iv_h_add,iv_h_delete,iv_h_update;
	

	private static final int PageSize = 25;
	private int searchType = 0;
	private String searchString = "";
	private int PageCountSize = 0;
	private String SaveMode = "";

	private int mYear,mMonth,mDay,hour, minute1;  
	private String datetype,timetype;
	static final int DATE_DIALOG_ID_S = 0;
	static final int DATE_DIALOG_ID_E = 1;
	static final int TIME_DIALOG_ID_S = 2; 
	static final int TIME_DIALOG_ID_E = 3;
	
	private DeviceSettingService mSettingService;
	private DeviceManager mDeviceManager;
	private MessageDialog mMessageDialog;
	private static ItemDiscountDialog mDisLinkItemDiscountDialog;
	private static ItemDiscountSetting dis;
	private String 	disLink = "";
	public static int MixMatchmode = 0;
	private MGCreateFiles mMGCreateFiles = new MGCreateFiles();
	private ItemPicService mItemPicService;
	private ItemSettingService itemservice = null;
	
	private DateSettingSelectionDialog mdssDialog;
	private TimeSettingSelectionDialog tdssDialog;
	private InputTimeInfoDialog itidDialog;
	private InputDateInfoDialog ididDialog;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_mm_setting);

		// =========== setup scanner =================
		mDeviceManager = DeviceManager.getInstance();
		mSettingService = ServiceManager.getInstance().mDeviceSettingService;
		mItemPicService = ServiceManager.getInstance().mItemPicService;
		
		List<ScannerSetting> scannerSettings = mSettingService
				.getScannerSettings();

		// check scanner
		int iScannerCount = scannerSettings.size();
		for (int i = 0; i < iScannerCount; i++) {
			int iPort = scannerSettings.get(i).getPort();
			for (int j = i + 1; j < iScannerCount; j++) {
				if (iPort == scannerSettings.get(j).getPort()) {
					// Toast.makeText(MixmatchsettingActivity.this,
					// " Scanner setup error. Please check.",
					// Toast.LENGTH_LONG).show();
					ShowMessage(" Scanner setup error. Please check.",
							MessageDialog.MESSAGE_BOX_OK,
							MessageDialog.ICON_INFO);
					finish();
				}

			}
		}

		for (int i = 0; i < scannerSettings.size(); i++) {
			BaseScanner baseScanner = new BaseScanner();
			baseScanner.setScannerSetting(scannerSettings.get(i));
			mDeviceManager.addScanner(baseScanner);
		}

		// open scanner
		for (int i = 0; i < mDeviceManager.scanners.size(); i++) {
			mDeviceManager.scanners.get(i).onConnect();
			mDeviceManager.scanners.get(i).setCallbackEvent(this);
			mDeviceManager.scanners.get(i).onEnableScanner();
		}

		// ============================================

		mmService = ServiceManager.getInstance().mMixMatchService;
		mdService = ServiceManager.getInstance().mMixMatchSettingService;
		depService = ServiceManager.getInstance().mDepartmantService;
		mDisLinkItemDiscountDialog = new ItemDiscountDialog(MixmatchSettingActivity.this, MixmatchSettingActivity.this);
		
		mdssDialog = new DateSettingSelectionDialog(this);
		tdssDialog = new TimeSettingSelectionDialog(this);
		itidDialog = new InputTimeInfoDialog(this, this);
		ididDialog = new InputDateInfoDialog(this, this);
		
		PosSetting item = ServiceManager.getInstance().mPosSettingService.Find();
		if(item == null){
			GlobalInfo.getInstance().calendar_type = false;
		}else{
			GlobalInfo.getInstance().calendar_type = item.isCalendarType();
		}
		getcontroller();

	}

	public void getcontroller() {

		sp_list = (Spinner) findViewById(R.id.sp_condition);
		sp_items = getResources().getStringArray(R.array.sp_condition_name);
		ArrayAdapter<String> SpAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, sp_items);
		SpAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		sp_list.setAdapter(SpAdapter);
		sp_list.setOnItemSelectedListener(onItemSelectedListener);

		lv_items = (ListView) findViewById(R.id.lv_item);
		lv_mm = (ListView) findViewById(R.id.lv_mm);
		lv_mm_detail_list  = (ListView) findViewById(R.id.lv_mm_detail);
		btn_search = (Button) findViewById(R.id.btn_search);
		ibtn_next = (ImageButton) findViewById(R.id.ibtn_next);
		btn_exit = (Button) findViewById(R.id.btn_exit);
		iv_h_add = (BeepImageButton) findViewById(R.id.iv_h_add);
		iv_h_delete = (BeepImageButton) findViewById(R.id.iv_h_delete);
		iv_h_update = (BeepImageButton) findViewById(R.id.iv_h_update);
		
		et_search = (EditText) findViewById(R.id.et_search);
		ibtn_backpage = (ImageButton) findViewById(R.id.ibtn_backpage);
		ibtn_nextpage = (ImageButton) findViewById(R.id.ibtn_nextpage);
		
		tv_page = (TextView) findViewById(R.id.tv_page);
		tv_dupc = (TextView) findViewById(R.id.tv_dupc);
		tv_dname = (TextView) findViewById(R.id.tv_dname);
		tv_ddesc = (TextView) findViewById(R.id.tv_ddesc);
		tv_dprice = (TextView) findViewById(R.id.tv_dprice);
		iv_photo = (ImageView) findViewById(R.id.iv_photo);

		ibtn_backpage.setOnClickListener(onClickListener);
		ibtn_nextpage.setOnClickListener(onClickListener);
		
		lv_items.setOnItemClickListener(onItemClickListener);
		lv_mm.setOnItemClickListener(onItemClickListener);
		lv_mm_detail_list.setOnItemClickListener(onItemClickListener);
		btn_search.setOnClickListener(onClickListener);
		ibtn_next.setOnClickListener(onClickListener);
		btn_exit.setOnClickListener(onClickListener);
		
		iv_h_add.setOnClickListener(onClickListener);
		iv_h_delete.setOnClickListener(onClickListener);
		iv_h_update.setOnClickListener(onClickListener);
		
		itemservice = ServiceManager.getInstance().mItemSettingService;
		
	//	btn_mm.addTextChangedListener(watcher);
		tv_page.setText(String.valueOf(1));
		SetEnabledTrue();
		loadMM();
		
	}
	
	private void loadMM(){
		
		mdlist = mdService.getmmdetaillist();
		if (mmAdapter == null) {
			mmAdapter = new MixMatchSelectionAdapter(this, mdlist);
			lv_mm_detail_list.setAdapter(mmAdapter);
		}else{
			//int i = list.size();
			mmAdapter.setSource(mdlist);
			mmAdapter.notifyDataSetChanged();
			
		}

		if (mdlist.size() > 0 ) {
			int index = mmAdapter.GetSelectedIndex();
				if (index  >= 0) {
					String ls = String.valueOf(mdlist.get(index).getMs_no());
					mmlist = mmService.getmmlistbyno(String.valueOf(mdlist.get(index).getMs_no()));
				 
					 setmmlist(mmlist);
					 mmAdapter.ScrollToRow(index);
					 lv_mm_detail_list.setSelection(index);
				}
		}
		
	}

	private TextWatcher watcher = new TextWatcher() {

		@Override
		public void afterTextChanged(Editable arg0) {
			// TODO Auto-generated method stub

		}

		@Override
		public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
				int arg3) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onTextChanged(CharSequence arg0, int arg1, int arg2,
				int arg3) {
			// TODO Auto-generated method stub
			// if(Status.ChangeMode == Status.User){
			// SetEnabledFalse();
			// }
//			String ls_mm = btn_mm.getText().toString();
//
//			mmlist = mmService.getmmlistbyno(ls_mm);
//			// if (mmlist != null && mmlist.size() > 0) {
//			setmmlist(mmlist);
			// }

		}

	};

	public void setmmlist(List<MixMatch> list) {

		if (mmitemAdapter == null) {
			mmitemAdapter = new MixMatchItemAdapter(this, list);
			lv_mm.setAdapter(mmitemAdapter);
		} else {
			//int i = list.size();
			mmitemAdapter.setSource(list);
			mmitemAdapter.notifyDataSetChanged();

		}
	}

	public OnClickListener onClickListener = new OnClickListener() {
		String pagetext = "";
		int page;
		String sql = "";
		String ms_no;
		String et_date, et_time,st_date, st_time;
		public void onClick(View view) {
			switch (view.getId()) {
			case R.id.ibtn_backpage:
				pagetext = (String) tv_page.getText();
				page = Integer.valueOf(pagetext);
				tv_page.setText(String.valueOf(page - 1));
				BindingData((page - 2), searchType, searchString);
				SetPage();
				itemAdapter.ScrollToRow(0);
				break;
			case R.id.ibtn_nextpage:
				pagetext = (String) tv_page.getText();
				page = Integer.valueOf(pagetext);
				tv_page.setText(String.valueOf(page + 1));
				BindingData(page, searchType, searchString);
				SetPage();
				itemAdapter.ScrollToRow(0);
				break;
			case R.id.ibtn_price_setting_clear_date:
				et_date = et_et_date.getText().toString();
				et_time = et_et_time.getText().toString();
				st_date = et_st_date.getText().toString();
				st_time = et_st_time.getText().toString();
				if (!et_date.equals("") || !et_time.equals("")
						|| !st_date.equals("") || !st_time.equals("")) {
					et_et_date.setText("");
					et_et_time.setText("");
					et_st_date.setText("");
					et_st_time.setText("");
				}
				break;
			case R.id.ibtn_clear_dis_link:
				if (!btn_dis_link.getText().equals("")) {
					btn_dis_link.setText("");
					dis = null;
					disLink = "";
				}
				break;
			case R.id.ll_right:
				Keyboard();
				break;
			case R.id.ll_middle:
				Keyboard();
				break;
			case R.id.btn_search:
				Keyboard();
				tv_page.setText(String.valueOf(1));
				Search();
				et_search.setText("");
				break;
//			case R.id.btn_mm:
//				Keyboard();
//				ControlID = R.id.btn_mm;
//				DialogWindows("MM", String.valueOf(btn_mm.getText()));
//				break;
			case R.id.ibtn_next:
				Keyboard();
				
				if (mdlist.size() <=0) {
					// Toast.makeText(MixmatchsettingActivity.this,
					// "MixMatch must not be empty.",
					// Toast.LENGTH_LONG).show();
					ShowMessage("MixMatch must not be empty.",
							MessageDialog.MESSAGE_BOX_OK,
							MessageDialog.ICON_INFO);
					return;
				}
				
				int index = itemAdapter.GetSelectedIndex();
				//
				String upc = list.get(index).getUpc();
				
				Departmant dep = depService.Find(list.get(index).getDep());
				
				if (list.get(index).getFollowdep().equals("1")?true:false) {
					if (dep !=null) {
						list.get(index).setScaleWeight(dep.getScale_weight()?"1":"0");
					}
				}
				
				if (list.get(index).getScaleWeight().equals("1")?true:false) {
					ShowMessage("A scalable item cannot be added into a mix match group.",
							MessageDialog.MESSAGE_BOX_OK,
							MessageDialog.ICON_INFO);
					return;
				}
				
				if (list.get(index).getIs_coupon().equals("1")?true:false) {
					ShowMessage("A coupon item cannot be added into a mix match group.",
							MessageDialog.MESSAGE_BOX_OK,
							MessageDialog.ICON_INFO);
					return;
				}
				
				index = mmAdapter.GetSelectedIndex();
				String ls_mm = String
						.valueOf(mdlist.get(index).getMs_no());
				
				MixMatch mm = new MixMatch();
				//
				if (!mmService.CheckMm(upc)) {
					mm.setMm_no(Integer.valueOf(ls_mm));
					mm.setUpc(upc);
					
					// mmlist.add(mm);

					 mmService.insertMm(mm);
					 if (GlobalInfo.getInstance().isMGNetwork) {
						MixMatch mmSettingx = mmService.FindMmByUPC(upc);
						mMGCreateFiles.createrFile(mmSettingx.toMGData("INSERT"));//UPDATE,DELETE
					 }
//					if (j <= 0) {
//						// Toast.makeText(MixmatchsettingActivity.this,
//						// "Save Error.",
//						// Toast.LENGTH_LONG).show();
//						ShowMessage("Save Error.",
//								MessageDialog.MESSAGE_BOX_OK,
//								MessageDialog.ICON_ERROR);
//					}else{
						if (mmService.checkitemprice(upc) == false) {
							mmService.InsertPriceMm(ls_mm,upc);
							
							if (GlobalInfo.getInstance().isMGNetwork) {
								PriceSetting price = ServiceManager.getInstance().mPriceService.getitempricesetting(upc);
								mMGCreateFiles.createrFile(price.toMGData("INSERT"));//UPDATE,DELETE
							 }
							
						}else{
							
							mmService.updateePriceMm2(ls_mm,upc);
							if (GlobalInfo.getInstance().isMGNetwork) {
								PriceSetting price = ServiceManager.getInstance().mPriceService.getitempricesetting(upc);
								mMGCreateFiles.createrFile(price.toMGData("UPDATE"));//UPDATE,DELETE
							 }
						}
//					}
					
					mmlist = mmService.getmmlistbyno(ls_mm,upc);
					setmmlist(mmlist);
					index = mmService.index - 1;
					
					mmitemAdapter.ScrollToRow(index);
					lv_mm.setSelection(index);
				} else {
					// Toast.makeText(MixmatchsettingActivity.this,
					// "The item is already in other group.",
					// Toast.LENGTH_LONG).show();
					ShowMessage("The item is already in other mix match group.",
							MessageDialog.MESSAGE_BOX_OK,
							MessageDialog.ICON_INFO);
				}
				break;
			case R.id.btn_exit:
				SaveMode = "";
				ShowMessage(
						getResources().getString(R.string.msg_exit_program),
						MessageDialog.MESSAGE_BOX_YES_NO,
						MessageDialog.ICON_INFO);
				break;
			case R.id.iv_h_add:
				MMDetailSettingWindow(null);
		
				break;
			case R.id.iv_h_delete:
				SaveMode = "Delete";
				if (mdlist.size() == 0)
					return;
				index = mmAdapter.GetSelectedIndex();
				 ms_no = String.valueOf(mdlist.get(index).getMs_no());	
				if (mmService.CheckMmbyno(ms_no)) {
					ShowMessage("Cannot delete a related Mix & Match.",
							MessageDialog.MESSAGE_BOX_OK,
							MessageDialog.ICON_INFO);
					return;
				}
				ShowMessage("Are you sure to delete this Mix&Match?",
						MessageDialog.MESSAGE_BOX_YES_NO,
						MessageDialog.ICON_INFO);
				break;
			case R.id.iv_h_update:
				
				index = mmAdapter.GetSelectedIndex();
				if (mdlist.size() >0) {
				    ms_no = String.valueOf(mdlist.get(index).getMs_no());					
					MMDetailSettingWindow(ms_no);
				}
				break;
			case R.id.ll_mm_detail:
				InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				inputMethodManager.hideSoftInputFromWindow(mmDialog
						.getWindow().getCurrentFocus().getWindowToken(),
						InputMethodManager.HIDE_NOT_ALWAYS);
				break;
			case R.id.btn_dis_link:
				if (mDisLinkItemDiscountDialog == null || mDisLinkItemDiscountDialog.isShowing())
					return;

				mDisLinkItemDiscountDialog.show();
				break;
			default:
				break;
			}
		}
	};
	
	Dialog mmDialog = null;
	EditText et_np_amt, et_np_price, et_st_date,
			et_st_time, et_et_date, et_et_time, et_pp_amt, et_pp_price,
			et_lq_amt, et_lq_price, et_da_price, et_percent_amt,et_ms_no,et_ms_desc;
	Button btn_price_setting_save, btn_price_setting_back,btn_dis_link;
	ImageButton ibtn_clear_date;
	private AbsoluteLayout  al_mm_detail;
   
	private void MMDetailSettingWindow(String ms_no) {
		if (mmDialog == null) {
			mmDialog = new Dialog(this, R.style.dialog2);
			mmDialog.setContentView(R.layout.dialog_perview_mm);
			Window win = mmDialog.getWindow();
			WindowManager.LayoutParams lp = win.getAttributes();
			lp.y = -50;
		}

		et_ms_no = (EditText) mmDialog
				.findViewById(R.id.et_ms_no);
		et_ms_desc = (EditText) mmDialog
				.findViewById(R.id.et_mm_desc);
		et_np_amt = (EditText) mmDialog
				.findViewById(R.id.et_price_setting_np_amt);
		et_np_price = (EditText) mmDialog
				.findViewById(R.id.et_price_setting_np_price);
		et_st_date = (EditText) mmDialog
				.findViewById(R.id.et_price_setting_st_date);
		et_st_time = (EditText) mmDialog
				.findViewById(R.id.et_price_setting_st_time);
		et_et_date = (EditText) mmDialog
				.findViewById(R.id.et_price_setting_et_date);
		et_et_time = (EditText) mmDialog
				.findViewById(R.id.et_price_setting_et_time);
		et_pp_amt = (EditText) mmDialog
				.findViewById(R.id.et_price_setting_pp_amt);
		et_pp_price = (EditText) mmDialog
				.findViewById(R.id.et_price_setting_pp_price);
		et_lq_amt = (EditText) mmDialog
				.findViewById(R.id.et_price_setting_lq_amt);
		et_lq_price = (EditText) mmDialog
				.findViewById(R.id.et_price_setting_lq_price);
		et_da_price = (EditText) mmDialog
				.findViewById(R.id.et_price_setting_da_price);
		et_percent_amt = (EditText) mmDialog
				.findViewById(R.id.et_price_setting_percent_amt);
		//et_mm = (EditText) mmDialog.findViewById(R.id.et_price_setting_mm);
		ibtn_clear_date = (ImageButton) mmDialog
				.findViewById(R.id.ibtn_price_setting_clear_date);
		ibtn_clear_dis_link = (ImageButton) mmDialog
				.findViewById(R.id.ibtn_clear_dis_link);
		ibtn_price_setting_clear_date = (ImageButton) mmDialog.findViewById(R.id.ibtn_price_setting_clear_date);
		btn_price_setting_save = (Button) mmDialog
				.findViewById(R.id.btn_price_setting_save);
		btn_price_setting_back = (Button) mmDialog
				.findViewById(R.id.btn_price_setting_back);
		al_mm_detail = (AbsoluteLayout) mmDialog
				.findViewById(R.id.ll_mm_detail);
		btn_dis_link = (Button) mmDialog.findViewById(R.id.btn_dis_link);
		
		et_da_price.addTextChangedListener(mmwatcher);
		et_et_date.addTextChangedListener(mmwatcher);
		et_et_time.addTextChangedListener(mmwatcher);
		et_lq_amt.addTextChangedListener(mmwatcher);
		et_lq_price.addTextChangedListener(mmwatcher);
		et_np_amt.addTextChangedListener(mmwatcher);
		et_np_price.addTextChangedListener(mmwatcher);
		et_percent_amt.addTextChangedListener(mmwatcher);
		et_pp_amt.addTextChangedListener(mmwatcher);
		et_pp_price.addTextChangedListener(mmwatcher);
		//et_mm.addTextChangedListener(mmwatcher);
		et_st_date.addTextChangedListener(mmwatcher);
		et_st_time.addTextChangedListener(mmwatcher);
		//et_ms_no.addTextChangedListener(mmwatcher);
		et_ms_desc.addTextChangedListener(mmwatcher);
		btn_dis_link.addTextChangedListener(mmwatcher);
		
		btn_dis_link.setOnClickListener(onClickListener);
		ibtn_clear_date.setOnClickListener(onClickListener);
		ibtn_price_setting_clear_date.setOnClickListener(onClickListener);
		ibtn_clear_dis_link.setOnClickListener(onClickListener);
		al_mm_detail.setOnClickListener(onClickListener);
		et_st_date.setOnClickListener(onTextClickListener);
		et_st_time.setOnClickListener(onTextClickListener);
		et_et_date.setOnClickListener(onTextClickListener);
		et_et_time.setOnClickListener(onTextClickListener);

		btn_price_setting_save.setOnClickListener(onClickPopupWindowListener);
		btn_price_setting_back.setOnClickListener(onClickPopupWindowListener);
		
		if (ms_no != null) {
			MixMatchmode = 0;
			//et_ms_no.setEnabled(false);
			RefresItemPrice(ms_no);
			SetPriceEnabledTrue();
			MixMatchmode = 1;
		}else{
			MixMatchmode = 0;
			//et_ms_no.setEnabled(true);
			
			//et_ms_no.setText(String.valueOf(mdService.getmaxno()));
			et_ms_no.setText(String.valueOf(getnextmmno(mdlist)));
			SetPriceEnabledTrue();
			setempty();
			MixMatchmode = 1;
		}
		
		mmDialog.show();

	}
	
	public void RefresItemPrice(String ms_no){
		MixMatch_detail md = new MixMatch_detail();
		//Item item = new Item ();
		dis = null;
		md = mdService.FindByNO(ms_no);
		//item = itemservice.getitem(upc);
		
//		et_cp_amt.setText((item.getMultple() <=1) ? "" :  String.valueOf(item.getMultple()));
//    	et_cp_price.setText(String.format("%.2f",item.getPrice()));
		
		if (md == null) {
			setempty();
		}else{
			et_ms_no.setText(String.valueOf(md.getMs_no()));
			et_ms_desc.setText(md.getMs_desc());
	    	et_da_price.setText((md.getDiscountamount() == null)? "" :String.valueOf(md.getDiscountamount()));
	    	et_et_date.setText(getdatetime(md.getEnddate()));
	    	et_et_time.setText(gettime(md.getEndtime()));
	    	et_lq_amt.setText((md.getLimitedqtyamount()== null || Integer.valueOf(md.getLimitedqtyamount()) < 1) ? "" :  String.valueOf(md.getLimitedqtyamount()));
	    	et_lq_price.setText((md.getLimitedqtyprice()== null)?"":String.format("%.2f",Double.valueOf(md.getLimitedqtyprice())));
	    	et_np_amt.setText( (md.getPriceMultiple()== null || Integer.valueOf(md.getPriceMultiple()) <= 1)?"":String.valueOf(md.getPriceMultiple()));
	    	
	    	et_np_price.setText((md.getPrice()== null)?"":String.format("%.2f",Double.valueOf(md.getPrice())));
	    	et_percent_amt.setText((md.getDiscountpercent()== null || Double.valueOf(md.getDiscountpercent()) < 0)?"":String.format("%.2f",Double.valueOf(md.getDiscountpercent())));
	    	et_pp_amt.setText((md.getPackagepricemultiple()== null || Integer.valueOf(md.getPackagepricemultiple()) <= 1) ? "" :  String.valueOf(md.getPackagepricemultiple()));
	    	et_pp_price.setText((md.getPackageprice()== null)?"":String.format("%.2f",Double.valueOf(md.getPackageprice())));
	    	et_st_date.setText(getdatetime(md.getStartdate()));
	    	et_st_time.setText(gettime(md.getStarttime()));
	    	
	    	disLink = (md.getDiscnt_link() == null) ? "" : md.getDiscnt_link();
			String ls_dis_name = ServiceManager.getInstance().mDiscountSettingService.getItemDiscountName(disLink.equals("")?"0":disLink);		
			btn_dis_link.setText((ls_dis_name == null) ? "" : String.valueOf(ls_dis_name));
		}
	}
	public OnClickListener onTextClickListener = new OnClickListener() {

		public void onClick(View view) {
			switch (view.getId()) {

			case R.id.et_price_setting_st_date:
				if (GlobalInfo.getInstance().calendar_type) {
					mdssDialog.show(R.id.et_price_setting_st_date,et_st_date.getText().toString());
				}else{
					ididDialog.show(R.id.et_price_setting_st_date,et_st_date.getText().toString());
				}
				break;
			case R.id.et_price_setting_st_time:
				if (GlobalInfo.getInstance().calendar_type) {
					tdssDialog.show(R.id.et_price_setting_st_time,et_st_time.getText().toString());
				}else{
					itidDialog.show(R.id.et_price_setting_st_time,et_st_time.getText().toString());
				}
				break;
			case R.id.et_price_setting_et_date:
				if (GlobalInfo.getInstance().calendar_type) {
					mdssDialog.show(R.id.et_price_setting_et_date,et_et_date.getText().toString());
				}else{
					ididDialog.show(R.id.et_price_setting_et_date,et_et_date.getText().toString());
				}
				break;
			case R.id.et_price_setting_et_time:
				if (GlobalInfo.getInstance().calendar_type) {
					tdssDialog.show(R.id.et_price_setting_et_time,et_et_time.getText().toString());
				}else{
					itidDialog.show(R.id.et_price_setting_et_time,et_et_time.getText().toString());
				}
				break;
			}

		}

	};
		
//	public void setdate(int id){
//			
//			EditText et_date = (EditText)mmDialog.findViewById(id);
//			String ls_date = et_date.getText().toString();
//			
//			Date curDate = null;
//			DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
//			// Date curDate =(Date)date;
//			try {
//				
//				curDate = format1.parse(ls_date);
//				
//			}catch(ParseException e) {
//				e.printStackTrace();
//			}
//			
//			Calendar c1 = Calendar.getInstance(); 
//			
//			if (curDate == null) {
//				 mYear = c1.get(Calendar.YEAR);  
//		        mMonth = c1.get(Calendar.MONTH);  
//		        mDay = c1.get(Calendar.DAY_OF_MONTH);  
//			}else{
//				c1.setTime(curDate);
//				mYear = c1.get(Calendar.YEAR);  
//			    mMonth = c1.get(Calendar.MONTH);  
//			    mDay = c1.get(Calendar.DAY_OF_MONTH);
//			}
//			
//	     
//		}
//	
//	
//	public void settime(int id){
//			
//			EditText et_time = (EditText)mmDialog.findViewById(id);
//			String ls_time = et_time.getText().toString();
//			
//			
//			if (ls_time.equals("") || ls_time == null) {
//				Calendar c1 = Calendar.getInstance(); 
//				hour = c1.get(Calendar.HOUR_OF_DAY);
//				minute1 = c1.get(Calendar.MINUTE);
//				
//			}else
//			{
//				String hourOfDay = ls_time.substring(0,2);
//				String minute = ls_time.substring(3);
//				
//				hour = Integer.valueOf(hourOfDay) ;  
//	            minute1 = Integer.valueOf(minute);  
//		     
//			}
//			
//		}
	
	public String getdatetime(String date){
		  
	  	Date curDate = null;
	  	String str;
		SimpleDateFormat  formatter  =  new  SimpleDateFormat("yyyy-MM-dd");
		DateFormat format1 = new SimpleDateFormat("yyyyMMdd");
		// Date curDate =(Date)date;
		try {
			if (date == null) {
				return "";
			}
			curDate = format1.parse(date);
			
		}catch(ParseException e) {
			e.printStackTrace();
		}
		if (curDate == null ) {
			 str ="";
		}else{
			str = formatter.format(curDate);
		}
		return str;
	};
	
	public String gettime(String time){
		
		 if (time == null || time.equals("")) {
			return "";
		}else{
			String str = time.substring(0,2);
			String str2 = time.substring(2);
			return str+":"+str2;
		}
		
		
	};
	
//	 OnDateSetListener mDateSetListener =new OnDateSetListener() {  
//         public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {  
//         	String date;
//             mYear = year;  
//             mMonth = monthOfYear;  
//             mDay = dayOfMonth;  
//              
//             date = (new StringBuilder().append(mYear)
//             		.append("-")
//             		.append(String.format("%02d",mMonth + 1))
//             		.append("-")
//             		.append(String.format("%02d",mDay))).toString();
//             
//             if(datetype.equals( "st_date")){
//             	 et_st_date.setText(date); 	
//             	 if (et_st_time.getText().toString().equals("")) {
//             		 et_st_time.setText("00:00");
//  				}
//             }else{
//             	 et_et_date.setText(date); 	
//             	 
//             	 if (et_et_time.getText().toString().equals("")) {
//             		 et_et_time.setText("23:59");
//  				}
//             }
//             
//             
//                       
//         }  
//     };  
//
//	 protected Dialog onCreateDialog(int id) {  
//	        switch (id) {  
//	         case DATE_DIALOG_ID_S:  
//	             return new DatePickerDialog(this,mDateSetListener,mYear, mMonth, mDay);
//	         case DATE_DIALOG_ID_E:  
//	         	 
//	             return new DatePickerDialog(this,mDateSetListener,mYear, mMonth, mDay);
//	         case TIME_DIALOG_ID_S:  
//	             return  new TimePickerDialog( this, mTimeSetListener, hour, minute1, true);
//	         case TIME_DIALOG_ID_E:  
//			        return new TimePickerDialog( this, mTimeSetListener, hour, minute1, true);
//			    }  
//			    return null;  
//	 } ;
//	 
//	 @Override
//	 public void onPrepareDialog(int id, Dialog dialog) {
//	    switch(id) {
//	    case DATE_DIALOG_ID_S :
//	     	  removeDialog(DATE_DIALOG_ID_S);
//	       break;
//	    case DATE_DIALOG_ID_E:  
//	 	   removeDialog(DATE_DIALOG_ID_E);
//	 	   break;
//	    case TIME_DIALOG_ID_S:  
//	 	   removeDialog(TIME_DIALOG_ID_S);
//	 	   break;
//	    case TIME_DIALOG_ID_E: 
//	 	   removeDialog(TIME_DIALOG_ID_E);
//	 	   break;
//		     
//	    }
//	 }
// 
//    OnTimeSetListener mTimeSetListener =   new TimePickerDialog.OnTimeSetListener()   
//    {  
//
//             @Override  
//             public void onTimeSet(TimePicker view, int hourOfDay, int minute) {  
//                 // TODO Auto-generated method stub  
//            	 String time;
//     			hour = hourOfDay;
//     			minute1 = minute;
//
//     			Calendar c1 = Calendar.getInstance();
//     			mYear = c1.get(Calendar.YEAR);
//     			mMonth = c1.get(Calendar.MONTH) + 1;
//     			mDay = c1.get(Calendar.DAY_OF_MONTH);
//     			time = String.format("%02d", hour) + ":"
//     					+ String.format("%02d", minute1);
//
//     			if (timetype.equals("st_time")) {
//     				et_st_time.setText(time);
//     				et_st_date.setText(mYear + "-" + mMonth + "-" + mDay);
//     			} else {
//     				et_et_time.setText(time);
//     				et_et_date.setText(mYear + "-" + mMonth + "-" + mDay);
//     			}
//             } 
//             
//            
//         };  
	
	OnClickListener onClickPopupWindowListener = new OnClickListener() {
		@Override
		public void onClick(View view) {
			// TODO Auto-generated method stub
			switch (view.getId()) {
			case R.id.btn_price_setting_save:
				if (validation() < 0) {
					return;
				}
				String upc2,
				da_price,
				et_date,
				et_time,
				lq_amt,
				lq_price,
				np_amt,
				np_price,
				percent_amt,
				pp_amt,
				pp_price,
				st_date,
				st_time,
				pmm,
				ms_no,
				ms_desc;
				
				
				ms_no = et_ms_no.getText().toString();
				ms_desc = et_ms_desc.getText().toString();
				da_price = et_da_price.getText().toString();
				et_date = et_et_date.getText().toString();
				et_time = et_et_time.getText().toString();
				lq_amt = et_lq_amt.getText().toString();
				lq_price = et_lq_price.getText().toString();
				np_amt = et_np_amt.getText().toString();
				np_price = et_np_price.getText().toString();
				percent_amt = et_percent_amt.getText().toString();
				pp_amt = et_pp_amt.getText().toString();
				pp_price = et_pp_price.getText().toString();
				st_date = et_st_date.getText().toString();
				st_time = et_st_time.getText().toString();
				if (dis != null){
					disLink = String.valueOf(dis.getDs_no());	
				}
				//pmm = et_mm.getText().toString();
				//Price price = new Price();
				MixMatch_detail mm = new MixMatch_detail();
				//price.setUpc(upc2);
				mm.setMs_no(Integer.valueOf(ms_no));
				mm.setMs_desc(ms_desc);
				mm.setPriceMultiple((!np_price.equals("")) ? (np_amt
						.equals("")) ? "1" : String.valueOf(np_amt) : null);
				mm.setPrice((np_price.equals("")) ? null : String
						.valueOf(np_price));
				mm.setStartdate((st_date.equals("")) ? null: st_date);
				mm.setStarttime((st_time.equals("")) ? null: st_time);
				mm.setEnddate((et_date.equals("")) ? null: et_date);
				mm.setEndtime((et_time.equals("")) ? null: et_time);
				mm.setPackagepricemultiple((!pp_price.equals("")) ? (pp_amt
						.equals("")) ? "1" : String.valueOf(pp_amt) : null);
				mm.setPackageprice((pp_price.equals("")) ? null : String
						.valueOf(pp_price));
				mm.setLimitedqtyamount((!lq_price.equals("")) ? (lq_amt
						.equals("")) ? "1" : String.valueOf(lq_amt) : null);
				mm.setLimitedqtyprice((lq_price.equals("")) ? null: String.valueOf(lq_price));
				mm.setDiscountamount((da_price.equals("")) ? null : String
						.valueOf(da_price));
				mm.setDiscountpercent((percent_amt.equals("")) ? null
						: String.valueOf(percent_amt));
				mm.setDiscnt_link((disLink.equals("")) ? null : disLink);
				//mm.setF01(upc2);
			//mm.setMm_no((pmm.equals("")) ? null : String.valueOf(pmm));

				if (mdService.checkitemm(ms_no) == false) {

//					if () {
						mdService.insertMmdetail(mm);
//						ShowMessage("Save completed.", MessageDialog.ICON_INFO,
//								MessageDialog.MESSAGE_BOX_OK);
					Toast.makeText(MixmatchSettingActivity.this,
								 "Save completed.",
								 Toast.LENGTH_SHORT).show();
					
					if (GlobalInfo.getInstance().isMGNetwork) {
						MixMatch_detail md = mdService.getMixMatchDetaile(ms_no);
						mMGCreateFiles.createrFile(md.toMGData("INSERT"));//UPDATE,DELETE
					 }
					
						MixMatchmode = 0;
						mmAdapter.ScrollToRow(mdlist.size());
						MixMatchmode = 1;
						if (mmDialog != null)
							mmDialog.dismiss();
//					} else {
//						ShowMessage("Save Error.", MessageDialog.ICON_ERROR,
//								MessageDialog.MESSAGE_BOX_OK);
//						return;
//					}
				} else {
//					if (> 0) {
						mdService.updateeMmdetail(mm);
//						ShowMessage("Save completed.", MessageDialog.ICON_INFO,
//								MessageDialog.MESSAGE_BOX_OK);
						Toast.makeText(MixmatchSettingActivity.this,
								 "Save completed.",
								 Toast.LENGTH_SHORT).show();
						
						if (GlobalInfo.getInstance().isMGNetwork) {
							MixMatch_detail md = mdService.getMixMatchDetaile(ms_no);
							mMGCreateFiles.createrFile(md.toMGData("UPDATE"));//UPDATE,DELETE
						 }
						MixMatchmode = 0;
						MixMatchmode = 1;
						if (mmDialog != null)
							mmDialog.dismiss();
//					} else {
//						ShowMessage("Save9999 Error.", MessageDialog.ICON_ERROR,
//								MessageDialog.MESSAGE_BOX_OK);
//						return;
//					}

				}

				//price_type = "0";
				
				SetPriceEnabledTrue();
				
				loadMM();
				break;
			case R.id.btn_price_setting_back:
				mmDialog.dismiss();
				break;
			
			}
		}
	};
	private TextWatcher mmwatcher = new TextWatcher() {

		public void afterTextChanged(Editable s) {
			// TODO Auto-generated method stub
		}

		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			// TODO Auto-generated method stub
		}

		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			// TODO Auto-generated method stub
			if (MixMatchmode == 1) {
				SetPriceEnabledFalse();// Fasle
			}
			
		}
	};
	
	public void SetPriceEnabledFalse() {
		btn_price_setting_save.setEnabled(true);
		btn_price_setting_back.setEnabled(true);
	}

	public void SetPriceEnabledTrue() {
		
		btn_price_setting_save.setEnabled(false);
		btn_price_setting_back.setEnabled(true);
	}

	public int getnextmmno(List<MixMatch_detail> list) {

		int li_mm = 1;
		for (int i = 0; i < list.size(); i++) {
			int j = list.get(i).getMs_no();
			if (j != i + 1) { // x閺勵垯缍樼憰浣瑰絻閸忋儳娈戦弫鏉跨摟閿涘[]閺勵垳骞囬張澶屾畱閺佹壆绮�				li_mm = i + 1; // 閹绘帒鍙嗙拠銉︽殶鐎涳拷
				break; // 鐠哄啿鍤顏嗗箚
			}
			// li_mm = j+1;

			li_mm = list.size() + 1;
		}

		return li_mm;
	}

	OnItemClickListener onItemClickDialogWindowListener = new OnItemClickListener() {

		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			// TODO Auto-generated method stub
			mmAdapter.ScrollToRow(position);

		}

	};

	public OnItemSelectedListener onItemSelectedListener = new OnItemSelectedListener() {

		public void onItemSelected(AdapterView<?> parent, View view,
				int position, long id) {
			if (sp_items[position].equals("ALL")) {
				et_search.setEnabled(false);
			} else {
				et_search.setEnabled(true);
			}
		}

		public void onNothingSelected(AdapterView<?> arg0) {

		}
	};

	public OnItemClickListener onItemClickListener = new OnItemClickListener() {

		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {

			switch (parent.getId()) {
			case R.id.lv_item:
				Keyboard();
				itemAdapter.ScrollToRow(position);
				if (list != null) {
					String upc = list.get(position).getUpc();
					tv_dupc.setText(upc);
					tv_dname.setText(list.get(position).getName());
					tv_ddesc.setText(list.get(position).getDesc());
					String priceText = "";
					if (list.get(position).getMultple() > 1) {
						priceText = String.valueOf(list.get(position).getMultple()) + "/";
					}
					tv_dprice.setText(priceText+String.format("%.2f",list.get(position).getPrice()));
					Bitmap bp = mItemPicService.getImageByUPC(upc);
					if (bp == null) {
						Bitmap logo = BitmapFactory.decodeResource(MixmatchSettingActivity.this
								.getApplicationContext().getResources(),
								R.drawable.moleqlogo);
						iv_photo.setImageBitmap(logo);
					} else {
						iv_photo.setImageBitmap(bp);
					}
				}
				break;
			case R.id.lv_mm:
				mmitemAdapter.ScrollToRow(position);
				break;
			case R.id.lv_mm_detail:
				mmAdapter.ScrollToRow(position);
				
				int index = mmAdapter.GetSelectedIndex();
				if (mdlist.size() > 0 ) {
					mmlist = mmService.getmmlistbyno(String.valueOf(mdlist.get(index).getMs_no()));
				
					 setmmlist(mmlist);
				}
				break;
			}
		}
	};

	public void Search() {
		searchString = et_search.getText().toString();
		switch ((int) sp_list.getSelectedItemId()) {
		case SP.Department:
			if (searchString != null && !searchString.trim().equals("")) {
				searchType = mdService.Department;
				if (MoleQUtil.isNumeric(searchString)) {
					PageCountSize = itemservice.GetPageCountSize(
							searchType, searchString);
					
					if (BindingData(0, searchType, searchString) == false) {
						ShowMessage("Item Not Found.",
								MessageDialog.MESSAGE_BOX_OK,
								MessageDialog.ICON_INFO);
						SetEnabledFalse();
					}
					SetPage();
				} else {
					if (list != null) {
						list.clear();
					}
				}
				//ControlEmpty();
			} else {
				et_search.setText("");
				return;
			}
			break;
		case SP.SubDepartment:
			if (searchString != null && !searchString.trim().equals("")) {
				searchType = mdService.SubDept;
				if (MoleQUtil.isNumeric(searchString)) {
					PageCountSize = itemservice.GetPageCountSize(
							searchType, searchString);
					if (BindingData(0, searchType, searchString) == false) {
						ShowMessage("Item Not Found.",
								MessageDialog.MESSAGE_BOX_OK,
								MessageDialog.ICON_INFO);
						SetEnabledFalse();
					}
					SetPage();
				} else {
					if (list != null) {
						list.clear();
					}
				}
				//ControlEmpty();
			} else {
				et_search.setText("");
				return;
			}
			break;
		case SP.UPC:
			if (searchString != null && !searchString.trim().equals("")) {
				searchType = mdService.UPC;
				if (searchString.length() < 14) {
					UPC upc = new UPC(searchString, UPC.INPUT_BY_MANUAL,
							GlobalInfo.getInstance().isNormalize);
					searchString = upc.code;
				}
				PageCountSize = itemservice.GetPageCountSize(
						searchType, searchString);
				if (BindingData(0, searchType, searchString) == false) {
					ShowMessage("Item Not Found.",
							MessageDialog.MESSAGE_BOX_OK,
							MessageDialog.ICON_INFO);
					SetEnabledFalse();
				}
				//ControlEmpty();
				SetPage();
			} else {
				et_search.setText("");
				return;
			}
			break;
		default:
			break;
		}
	}
	
	public boolean BindingData(int page, int SPType, String searchString) {
		if (list == null) {
			list = new ArrayList<ItemSetting>();
			list = itemservice.SearchItems(page, SPType,
					searchString);

			itemAdapter = new ItemListAdapter(this, list);
			lv_items.setAdapter(itemAdapter);
			if (list.size() > 0) {
				tv_page.setVisibility(View.VISIBLE);
				ibtn_next.setEnabled(true);
	
				String upc = list.get(0).getUpc();
				tv_dupc.setText(upc);
				tv_dname.setText(list.get(0).getName());
				tv_ddesc.setText(list.get(0).getDesc());
				String priceText = "";
				if (list.get(0).getMultple() > 1) {
					priceText = String.valueOf(list.get(0).getMultple()) + "/";
				}
				tv_dprice.setText(priceText+String.format("%.2f",list.get(0).getPrice()));
				Bitmap bp = mItemPicService.getImageByUPC(upc);
				if (bp == null) {
					Bitmap logo = BitmapFactory.decodeResource(MixmatchSettingActivity.this
							.getApplicationContext().getResources(),
							R.drawable.moleqlogo);
					iv_photo.setImageBitmap(logo);
				} else {
					iv_photo.setImageBitmap(bp);
				}
				return true;
			} else {
				tv_page.setVisibility(View.INVISIBLE);
				ibtn_next.setEnabled(false);
				tv_dupc.setText("");
				tv_dname.setText("");
				tv_ddesc.setText("");
				tv_dprice.setText("");
				Bitmap bp = mItemPicService.getImageByUPC("");
				if (bp == null) {
					Bitmap logo = BitmapFactory.decodeResource(MixmatchSettingActivity.this
							.getApplicationContext().getResources(),
							R.drawable.moleqlogo);
					iv_photo.setImageBitmap(logo);
				} else {
					iv_photo.setImageBitmap(bp);
				}
				return false;
			}
		}else{
			list.clear();
			list = itemservice.SearchItems(page, SPType,
					searchString);
			itemAdapter.setSource(list);
			itemAdapter.notifyDataSetChanged();
			if (list.size() > 0) {
				tv_page.setVisibility(View.VISIBLE);
				// int index = itemAdapter.GetSelectedIndex();
//				RefresItem(0);
				ibtn_next.setEnabled(true);
				return true;
			} else {
				tv_page.setVisibility(View.INVISIBLE);
				ibtn_next.setEnabled(false);
				tv_dupc.setText("");
				tv_dname.setText("");
				tv_ddesc.setText("");
				tv_dprice.setText("");
				Bitmap bp = mItemPicService.getImageByUPC("");
				if (bp == null) {
					Bitmap logo = BitmapFactory.decodeResource(MixmatchSettingActivity.this
							.getApplicationContext().getResources(),
							R.drawable.moleqlogo);
					iv_photo.setImageBitmap(logo);
				} else {
					iv_photo.setImageBitmap(bp);
				}
				//setempty();
				return false;
			}
		}
		
	}

	public class SP {
		public static final int Department = 0;
		public static final int SubDepartment = 1;
		public static final int UPC =   2;		
	// public static final int ALL = 2;

	}

	public void SetPage() {
		ibtn_backpage = (ImageButton) findViewById(R.id.ibtn_backpage);
		ibtn_nextpage = (ImageButton) findViewById(R.id.ibtn_nextpage);
		tv_page = (TextView) findViewById(R.id.tv_page);
		String pagetext = (String) tv_page.getText();
		int page = Integer.valueOf(pagetext);
		if (PageCountSize > page) {
			ibtn_nextpage.setEnabled(true);
			ibtn_nextpage.setVisibility(View.VISIBLE);
		} else {
			ibtn_nextpage.setEnabled(false);
			ibtn_nextpage.setVisibility(View.INVISIBLE);
		}

		if (PageCountSize > 1 && page > 1) {
			ibtn_backpage.setEnabled(true);
			ibtn_backpage.setVisibility(View.VISIBLE);
		} else {
			ibtn_backpage.setEnabled(false);
			ibtn_backpage.setVisibility(View.INVISIBLE);
		}
	}

	public void SetEnabledTrue() {
		ibtn_next.setEnabled(false);
		// btn_update.setEnabled(false);
		ibtn_backpage.setEnabled(false);
		ibtn_nextpage.setEnabled(false);
		ibtn_backpage.setVisibility(View.INVISIBLE);
		ibtn_nextpage.setVisibility(View.INVISIBLE);
		tv_page.setVisibility(View.INVISIBLE);
	}

	public void SetEnabledFalse() {
		ibtn_next.setEnabled(false);
		//btn_update.setEnabled(true);
	}

	public boolean isNumeic(String str) {
		Pattern pattern = Pattern.compile("[0-9]*");
		Matcher isNum = pattern.matcher(str);
		if (!isNum.matches()) {
			return false;
		}
		return true;
	}

	public void Keyboard() {
		InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		inputMethodManager.hideSoftInputFromWindow(MixmatchSettingActivity.this
				.getCurrentFocus().getWindowToken(),
				InputMethodManager.HIDE_NOT_ALWAYS);
	}

	public void DeleteMessage(int msg) {
		switch (msg) {
		case 0:
			// Toast.makeText(MixmatchsettingActivity.this,
			// "Delete Error.",
			// Toast.LENGTH_LONG).show();
			ShowMessage("Delete Error.", MessageDialog.MESSAGE_BOX_OK,
					MessageDialog.ICON_ERROR);
			break;
		case 1:
			// Toast.makeText(FlipChartSettingActivity.this,
			// "Delete Completed.",
			// Toast.LENGTH_LONG).show();
			break;
		}
	}

	public void DeleteMiaMatch(String upc) {
		int index = mmAdapter.GetSelectedIndex();
		String mm_no = String.valueOf(mdlist.get(index).getMs_no());	
		index = mmitemAdapter.GetSelectedIndex();
		int index2 = -1;
		if (index == 0 && mmlist.size() > 1) {
			index2 = index;
//			ms_no = String
//					.valueOf(mdlist.get(index2 + 1).getMs_no());
		} else if (index > 0) {
			index2 = index - 1;
			//ms_no = String.valueOf(mdlist.get(index2).getMs_no());
		}
		
		if (GlobalInfo.getInstance().isMGNetwork) {
			MixMatch mm = mmService.FindMmByUPC(upc);
			mMGCreateFiles.createrFile(mm.toMGData("DELETE"));//UPDATE,DELETE
		}
		mmService.DeleteMm(mm_no, upc);
		 
		if (mmService.checkitemprice(upc) == true) {
			mmService.updateePriceMm(mm_no, upc);
			
			if (GlobalInfo.getInstance().isMGNetwork) {
				PriceSetting p = ServiceManager.getInstance().mPriceService.getitempricesetting(upc);
				mMGCreateFiles.createrFile(p.toMGData("UPDATE"));//UPDATE,DELETE
			 }
		}
//		DeleteMessage(msg);
		mmitemAdapter.ScrollToRow(index2);
		 lv_mm.setSelection(index2);
		 
		mmlist = mmService.getmmlistbyno(mm_no);
		mmitemAdapter.setSource(mmlist);
		mmitemAdapter.notifyDataSetChanged();
	}

	// =========== setup scanner =================
	public void onErrorEvent(String res) {
		// TODO Auto-generated method stub

	}

	public void onScannerEvent(String res) {
		//ibtn_next.setEnabled(false);
		sp_list.setSelection(SP.UPC);
		et_search.setText(res);
		Keyboard();
		tv_page.setText(String.valueOf(1));
		this.Search();
		et_search.setText("");
		//ibtn_next.setEnabled(true);
	}

	public void onTimeOutEvent() {
		// TODO Auto-generated method stub

	}

	public void onWeightEvent(int arg0) {
		// TODO Auto-generated method stub

	}
	
	public int gettime_short(String time){
			
			int str;
			  if (time == null) {
				str = 0;
				}else
				{
				     str = Integer.valueOf(time.replace(":","")) ;
				}	
				return  str;
	
		};
	
	public void setempty(){
		
    	et_da_price.setText("");
    	et_et_date.setText("");
    	et_et_time.setText("");
    	et_lq_amt.setText("");
    	et_lq_price.setText("");
    	et_np_amt.setText("");
    	et_np_price.setText("");
    	et_percent_amt.setText("");
    	et_pp_amt.setText("");
    	et_pp_price.setText("");
    	et_st_date.setText("");
    	et_st_time.setText("");
    	//et_ms_no.setText("");
    	et_ms_desc.setText("");
    	btn_dis_link.setText("");
    	disLink = "";
    	dis = null;
	}
	
	public static boolean isNum(String str){
		return str.matches("^[-+]?(([0-9]+)([.]([0-9]+))?|([.]([0-9]+))?)$");
	}
	
	public int validation(){
			
			String da_price,ms_desc,et_date,et_time,lq_amt,lq_price,np_amt,np_price,percent_amt,pp_amt,pp_price,st_date,st_time,pmm,cp_price,cp_amt;
			
			ms_desc =et_ms_desc.getText().toString();
		    et_date = et_et_date.getText().toString();
		    et_time =et_et_time.getText().toString();
		    lq_amt =et_lq_amt.getText().toString();
		    lq_price=et_lq_price.getText().toString();
		    np_amt = et_np_amt.getText().toString();
		    np_price =et_np_price.getText().toString();
		    percent_amt =et_percent_amt.getText().toString();
		    da_price = et_da_price.getText().toString();
		    pp_amt =et_pp_amt.getText().toString();
		    pp_price = et_pp_price.getText().toString();
		    st_date = et_st_date.getText().toString();
		    st_time = et_st_time.getText().toString();
		   // pmm = et_mm.getText().toString();
		    boolean zeroPrice = false;
			zeroPrice = GlobalInfo.getInstance().isZeroPrice;
		    
		    if (ms_desc.equals("")) {
		    	ShowMessage("Description can not be empty.",MessageDialog.ICON_INFO,MessageDialog.MESSAGE_BOX_OK);
		    	return -1;
			}
//		    
//		    if (!cp_price.equals("") && isNum(cp_price) == false) {
//		    	ShowMessage("Please enter a valid Current Price.",MessageDialog.ICON_INFO,MessageDialog.MESSAGE_BOX_OK);
//		    	return -1;
//			}
		    
		    
		    if (!np_amt.equals("") && np_price.equals("")) {
		    	ShowMessage("Next Price can not be empty.",MessageDialog.ICON_INFO,MessageDialog.MESSAGE_BOX_OK);
		    	return -1;
			}
		    
		    if (!np_price.equals("") && isNum(np_price) == false) {
		    	ShowMessage("Please enter a valid Next Price.",MessageDialog.ICON_INFO,MessageDialog.MESSAGE_BOX_OK);
		    	return -1;
			}
		    
		    if (!np_price.equals("") && Double.valueOf(np_price) == 0 && !zeroPrice) {
				// Toast.makeText(PriceSettingActivity.this,
				// "Please enter a valid Current Price.",
				// Toast.LENGTH_LONG).show();
		    	ShowMessage("Item Price cannot be zero.",MessageDialog.ICON_INFO,MessageDialog.MESSAGE_BOX_OK);
				et_np_price.requestFocus();
				return -1;
			}
		    
		    if (!pp_amt.equals("") && pp_price.equals("")) {
		    	ShowMessage("Pkg Price can not be empty.",MessageDialog.ICON_INFO,MessageDialog.MESSAGE_BOX_OK);
		    	return -1;
			}
		    
		    if (!pp_price.equals("") && isNum(pp_price) == false) {
		    	ShowMessage("Please enter a valid Pkg Price.",MessageDialog.ICON_INFO,MessageDialog.MESSAGE_BOX_OK);
		    	return -1;
			}
		    
		    if (!pp_price.equals("") && Double.valueOf(pp_price) == 0 && !zeroPrice) {
		    	ShowMessage("Item Price cannot be zero.",MessageDialog.ICON_INFO,MessageDialog.MESSAGE_BOX_OK);
				et_pp_price.requestFocus();
				return -1;
			}
		    
		    if (da_price.equals("0")) {
				ShowMessage("Discount Amount can not be zero.",
						MessageDialog.MESSAGE_BOX_OK, MessageDialog.ICON_INFO);
				return -1;
			}
			
			if (percent_amt.equals("0")) {
				ShowMessage("Discount Rate can not be zero.",
						MessageDialog.MESSAGE_BOX_OK, MessageDialog.ICON_INFO);
				return -1;
			}
			
			if (lq_amt.equals("0")) {
				// Toast.makeText(PriceSettingActivity.this,
				// "Limited Price can not be empty.",
				// Toast.LENGTH_LONG).show();
				ShowMessage("Limited Qty can not be zero.",
						MessageDialog.MESSAGE_BOX_OK, MessageDialog.ICON_INFO);
				return -1;
			}
			
			if (!lq_price.equals("") && lq_amt.equals("")) {
				// Toast.makeText(PriceSettingActivity.this,
				// "Limited Price can not be empty.",
				// Toast.LENGTH_LONG).show();
				ShowMessage("Limited Qty can not be empty.",
						MessageDialog.MESSAGE_BOX_OK, MessageDialog.ICON_INFO);
				return -1;
			}
		    
		    if (!lq_amt.equals("") && lq_price.equals("")) {
		    	ShowMessage("Limited Price can not be empty.",MessageDialog.ICON_INFO,MessageDialog.MESSAGE_BOX_OK);
		    	return -1;
			}
		    
		    if (!lq_price.equals("") && isNum(lq_price) == false) {
		    	ShowMessage("Please enter a valid Limited Price.",MessageDialog.ICON_INFO,MessageDialog.MESSAGE_BOX_OK);
		    	return -1;
			}
		    
		    if (!lq_price.equals("") && Double.valueOf(lq_price) == 0 && !zeroPrice) {
		    	ShowMessage("Item Price cannot be zero.",MessageDialog.ICON_INFO,MessageDialog.MESSAGE_BOX_OK);
		    	et_lq_price.requestFocus();
		    	return -1;
			}
		    
		    if (!st_date.equals("") && st_time.equals("")) {
		    	ShowMessage("Start Time can not be empty.",MessageDialog.ICON_INFO,MessageDialog.MESSAGE_BOX_OK);
		    	return -1;
			}
		    
		    if (!st_date.equals("") && st_time.equals("")) {
		    	ShowMessage("Start Time can not be empty.",MessageDialog.ICON_INFO,MessageDialog.MESSAGE_BOX_OK);
		    	return -1;
			}
		    
		    if (!et_date.equals("") && et_time.equals("")) {
		    	ShowMessage("End Time can not be empty.",MessageDialog.ICON_INFO,MessageDialog.MESSAGE_BOX_OK);
		    	return -1;
			}
		    
		    if (st_date.equals("") && !st_time.equals("")) {
		    	ShowMessage("Start Date can not be empty.",MessageDialog.ICON_INFO,MessageDialog.MESSAGE_BOX_OK);
		    	return -1;
			}
		    
		    if (et_date.equals("") && !et_time.equals("")) {
		    	ShowMessage("End Date can not be empty.",MessageDialog.ICON_INFO,MessageDialog.MESSAGE_BOX_OK);
		    	return -1;
			}
		    
		    if( !percent_amt.equals("") && Double.valueOf(percent_amt) > 100){
		    	ShowMessage("Cannot be more than 100%.",MessageDialog.ICON_INFO,MessageDialog.MESSAGE_BOX_OK);
		    	return -1;
		    }
		    
//		    if (cp_price.equals("")) {
//		    	ShowMessage("Current Price can not be empty.",MessageDialog.ICON_INFO,MessageDialog.MESSAGE_BOX_OK);
//		    	return -1;
//		     }
			    
			    Date curDate_s = null,curDate_e = null;
				DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
				// Date curDate =(Date)date;
				try {
					
					curDate_s = format1.parse(st_date);
					curDate_e = format1.parse(et_date);
					
				}catch(ParseException e) {
					e.printStackTrace();
				}
			    
				if(!et_date.equals("") && !st_date.equals("")){
					 if( curDate_e.before(curDate_s)){
					    	ShowMessage("End Date cannot be earilier than Start Date.",MessageDialog.ICON_INFO,MessageDialog.MESSAGE_BOX_OK);
					    	return -1;
					    }
					    
					 if (!st_time.equals("") && !et_time.equals("") ) {
						 if (et_date.equals(st_date) &&  gettime_short(et_time) < gettime_short(st_time) ) {
						    	ShowMessage("End Time cannot be earilier than Start Time.",MessageDialog.ICON_INFO,MessageDialog.MESSAGE_BOX_OK);
						    	return -1;
							}
					}
					       
				}
			
			return 1;
		}

	private OnClickMessageListener onClickMessageListener = new OnClickMessageListener() {

		@Override
		public void onClickYes() {
			// TODO Auto-generated method stub
			if (SaveMode.equals("Delete")) {
				String ms_no = "";
				int index = mmAdapter.GetSelectedIndex();
				int index2 = -1;
				if (index == 0 && mdlist.size() > 1) {
					index2 = index;
//					ms_no = String
//							.valueOf(mdlist.get(index2 + 1).getMs_no());
				} else if (index > 0) {
					index2 = index - 1;
					//ms_no = String.valueOf(mdlist.get(index2).getMs_no());
				}
				ms_no = String
						.valueOf(mdlist.get(index).getMs_no());
				if (GlobalInfo.getInstance().isMGNetwork) {
					MixMatch_detail mmd = mdService.getMixMatchDetaile(ms_no);
					mMGCreateFiles.createrFile(mmd.toMGData("DELETE"));//UPDATE,DELETE
				}
				mdService.DeleteMmdetail(ms_no);
				
				mmAdapter.ScrollToRow(index2);
				 lv_mm_detail_list.setSelection(index2);
				loadMM();
				mMessageDialog.dismiss();
			} else {
				mDeviceManager.disableAllScanner();
				mDeviceManager.disconnectAllScanner();
				mDeviceManager.resetALLDevices();
				finish();
			}
		}

		@Override
		public void onClickNo() {
			// TODO Auto-generated method stub

			mDeviceManager.clearAllScannerBuffer();
			mDeviceManager.enableAllScanner();
			mMessageDialog.dismiss();
		}

		@Override
		public void onClickOK() {
			// TODO Auto-generated method stub

			mDeviceManager.clearAllScannerBuffer();
			mDeviceManager.enableAllScanner();
			mMessageDialog.dismiss();
		}

	};

	public void ShowMessage(String ls_msg, int style, int icon) {
		mMessageDialog = new MessageDialog(MixmatchSettingActivity.this);
		mMessageDialog.setStyle(style);
		mMessageDialog.setMessageIcon(icon);
		mMessageDialog.setMessage(ls_msg);
		mMessageDialog.setOnClickMessageListener(onClickMessageListener);
		mMessageDialog.show();
	}

	@Override
	public void onDataEvent(Object obj) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onReturnValue(int what, Object obj) {
		// TODO Auto-generated method stub
		dis= (ItemDiscountSetting)obj;
		btn_dis_link.setText(String.valueOf(dis.getDs_desc()));
	}
	
	@Override
	public void onCloseWithReturn(Class<? extends MoleQBaseDialog> pramClass, int viewId, String parm) {
		super.onCloseWithReturn(pramClass, viewId, parm);
		
		Calendar c1 = Calendar.getInstance();
		mYear = c1.get(Calendar.YEAR);
		mMonth = c1.get(Calendar.MONTH) + 1;
		mDay = c1.get(Calendar.DAY_OF_MONTH);
		String time = String.format("%02d", 00) + ":"
				+ String.format("%02d", 00);
		String time2 = String.format("%02d", 23) + ":"
				+ String.format("%02d", 59);
		switch (viewId) {
		case R.id.et_price_setting_st_date:
			et_st_date.setText(parm);
			if (et_st_time.getText().toString().equals("")) {
				et_st_time.setText(time);
			}
			break;
		case R.id.et_price_setting_st_time:
			et_st_time.setText(parm);
			if (et_st_date.getText().toString().equals("")) {
				et_st_date.setText(mYear + "-" + mMonth + "-" + mDay);
			}
			break;
		case R.id.et_price_setting_et_date:
			et_et_date.setText(parm);
			if (et_et_time.getText().toString().equals("")) {
				et_et_time.setText(time2);
			}
			break;
		case R.id.et_price_setting_et_time:
			et_et_time.setText(parm);
			if (et_et_date.getText().toString().equals("")) {
				et_et_date.setText(mYear + "-" + mMonth + "-" + mDay);
			}
			break;
		default:
			break;
		}
		
	}

	

}